/*
 * Copyright (c) 2010, VeRSI Consortium
 *   (Victorian eResearch Strategic Initiative, Australia)
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the VeRSI, the VeRSI Consortium members, nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package versi.vitro.oaiserviceprovider.helper;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;

import org.apache.log4j.Logger;

/**
 * Service implementing {@link GeneralHelper}.
 */
public class GeneralHelperImpl implements GeneralHelper {

    /** log4j instance. */
    private static final Logger LOGGER = Logger.getLogger(GeneralHelperImpl.class);

    /**
     * Default Constructor.
     */
    public GeneralHelperImpl() {
	super();
    }

    /** {@inheritDoc} */
    public byte[] getFileAsByteArray(final File file) {
	byte[] fileContent = null;
	FileInputStream inputStream = null;
	try {
	    inputStream = new FileInputStream(file);
	    fileContent = new byte[(int) file.length()];
	    inputStream.read(fileContent);

	} catch (IOException ioException) {
	    String message = "Cannot read file for reading into byte array: " + file;
	    LOGGER.error(message, ioException);
	    throw new RuntimeException(message, ioException);
	} finally {
	    try {
		if (inputStream != null) {
		    inputStream.close();
		}
	    } catch (IOException ioException) {
		String message = "Cannot close file after reading into byte array: " + file;
		LOGGER.error(message, ioException);
		throw new RuntimeException(message, ioException);
	    }
	}
	return fileContent;
    }

    /** {@inheritDoc} */
    public void writeByteArrayToLocalFile(final byte[] fileByteArray, final String filePath) {

	File file = new File(filePath);
	FileOutputStream outputStream = null;
	try {
	    outputStream = new FileOutputStream(file);
	    outputStream.write(fileByteArray);
	} catch (FileNotFoundException fileNotFoundException) {
	    String message = "Cannot find file for writing byte array: " + filePath;
	    LOGGER.error(message, fileNotFoundException);
	    throw new RuntimeException(message, fileNotFoundException);
	} catch (IOException ioException) {
	    String message = "Cannot write byte array to file: " + filePath;
	    LOGGER.error(message, ioException);
	    throw new RuntimeException(message, ioException);
	} finally {
	    try {
		if (outputStream != null) {
		    outputStream.close();
		}
	    } catch (IOException ioException) {
		String message = "Cannot close file after writing into byte array: " + file;
		LOGGER.error(message, ioException);
		throw new RuntimeException(message, ioException);
	    }
	}
	LOGGER.info("File has been created on " + filePath.toString());

    }

    /** {@inheritDoc} */
    public String readFileAsString(final String filePath) {
	StringBuffer fileData = new StringBuffer(1000);
	BufferedReader reader = null;
	try {
	    reader = new BufferedReader(new FileReader(filePath));
	    char[] buf = new char[1024];
	    int numRead = 0;
	    while ((numRead = reader.read(buf)) != -1) {
		String readData = String.valueOf(buf, 0, numRead);
		fileData.append(readData);
		buf = new char[1024];
	    }
	    reader.close();
	} catch (FileNotFoundException fileNotFoundException) {
	    String message = "Cannot find file: " + filePath;
	    LOGGER.error(message, fileNotFoundException);
	    throw new RuntimeException(message, fileNotFoundException);
	} catch (IOException ioException) {
	    String message = "Cannot read file: " + filePath;
	    LOGGER.error(message, ioException);
	    throw new RuntimeException(message, ioException);
	} finally {
	    try {
		if (reader != null) {
		    reader.close();
		}
	    } catch (IOException ioException) {
		String message = "Cannot close file after writing into byte array: " + filePath;
		LOGGER.error(message, ioException);
		throw new RuntimeException(message, ioException);
	    }
	}
	return fileData.toString();
    }

    /** {@inheritDoc} */
    @SuppressWarnings("unchecked")
    public String readResourceAsString(final String resourcePath) {

	Class clazz = getClass();
	return readPackageResourceAsString(resourcePath, clazz);
    }

    /** {@inheritDoc} */
    @SuppressWarnings("unchecked")
    public String readPackageResourceAsString(final String resourcePath, final Class clazz) {
	InputStream resourceAsStream = clazz.getResourceAsStream(resourcePath);
	InputStreamReader inputStreamReader = new InputStreamReader(resourceAsStream);
	BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

	StringWriter stringWriter = new StringWriter();
	PrintWriter printWriter = new PrintWriter(stringWriter);

	int intValue;
	try {
	    while ((intValue = bufferedReader.read()) != -1) {
		printWriter.write(intValue);
	    }
	} catch (IOException ioException) {
	    String message = "Cannot read resource: " + resourcePath;
	    LOGGER.error(message, ioException);
	    throw new RuntimeException(message, ioException);
	} finally {
	    try {
		if (resourceAsStream != null) {
		    resourceAsStream.close();
		}
	    } catch (IOException ioException) {
		String message = "Cannot close file after writing into byte array: " + resourcePath;
		LOGGER.error(message, ioException);
		throw new RuntimeException(message, ioException);
	    }
	}
	return stringWriter.toString();
    }
}
